package com.boot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.dto.PageDTO;
import com.boot.entity.Result;
import com.boot.entity.SysRole;
import com.boot.service.ISysRoleService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/sys-role")
public class SysRoleController {

    @Resource
    private ISysRoleService roleService;

    @GetMapping("/page")
    public Result<Page<SysRole>> page(PageDTO pageDTO) {
        Page<SysRole> page = new Page<>(pageDTO.getPage(), pageDTO.getSize());
        Page<SysRole> rolePage = roleService.page(page);
        return Result.success(rolePage);
    }

    @GetMapping
    public Result<List<SysRole>> list() {
        return Result.success(roleService.list());
    }

    @GetMapping("/{id}")
    public Result<SysRole> getById(@PathVariable Long id) {
        SysRole role = roleService.getById(id);
        if (role == null) return Result.fail("角色不存在");
        return Result.success(role);
    }

    @PostMapping
    public Result<String> add(@Valid @RequestBody SysRole role) {
        if (role.getName() == null || role.getName().trim().isEmpty()) {
            return Result.fail("角色名称不能为空");
        }
        if (role.getCode() == null || role.getCode().trim().isEmpty()) {
            return Result.fail("角色编码不能为空");
        }

        if (roleService.save(role)) {
            return Result.success("添加成功");
        }
        return Result.fail("添加失败");
    }

    @PutMapping
    public Result<String> update(@RequestBody SysRole role) {
        if (roleService.updateById(role)) {
            return Result.success("更新成功");
        }
        return Result.fail("更新失败");
    }

    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        if (roleService.removeById(id)) {
            return Result.success("删除成功");
        }
        return Result.fail("删除失败");
    }
}
